package com.s64.ssm.controller;

import com.google.code.kaptcha.Producer;
import com.s64.ssm.entity.LoginVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;

@Controller
public class LoginController {
    @Autowired
    private Producer producer;

    @GetMapping("/login")
    public String login() {
        return "login";
    }

    @PostMapping("/login")
    public String login(LoginVO loginVO, HttpSession session, Model model) {
        String code = (String) session.getAttribute("code");
        if (!code.equalsIgnoreCase(loginVO.getCode())) {
            model.addAttribute("msg", "验证码不正确");
            return "login";
        }

        // 省略验证用户名密码的逻辑
        // 登陆成功
        return "redirect:/users";
    }

    @GetMapping("/kaptcha")
    public void kaptcha(HttpServletResponse response, HttpSession session) throws IOException {
        String text = producer.createText();
        session.setAttribute("code", text);

        BufferedImage image = producer.createImage(text);
        response.setContentType("image/png");
        ImageIO.write(image, "png", response.getOutputStream());
    }
}
